package com.zueb.stumanage.login

import android.app.Application
import androidx.databinding.ObservableField
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.hjq.toast.ToastUtils
import com.zueb.stumanage.MyAppliaction
import com.zueb.stumanage.logic.model.LoginData
import com.zueb.stumanage.logic.model.UserLogin
import com.zueb.stumanage.logic.network.MyService
import com.zueb.stumanage.util.Preference
import kotlinx.coroutines.launch


class LoginViewModel(application: Application): AndroidViewModel(application) {

     val uname = ObservableField<String>()
     val upwd = ObservableField<String>()
    val loginOK = MutableLiveData<Boolean>()
    fun login(){
        val _userId = uname.get()
        val _password = upwd.get()
        if (_userId != null&&_password!=null) {
            var _user= LoginData(_userId.toInt(),_password)
            viewModelScope.launch {
                val userLoginResponse = MyService.api.userLogin(_user)
                if(userLoginResponse.code == "200"){
                  ToastUtils.show("登录成功")
                    loginOK.value = true
                    //存储登录状态
                   var Status:Boolean by Preference(
                       MyAppliaction.context,"Status",false
                   )
                    Status=true;
                    //存储登录个人数据
                    var userInfo: UserLogin by Preference(
                        MyAppliaction.context,"user",
                        UserLogin(0,0,"null","null",0,0,"null",0,"null")
                    )
                    userInfo = userLoginResponse.data
                    //存储登录的个人权限功能数组
                    var privileges:List<String> by Preference(
                        MyAppliaction.context,"privileges",
                        listOf("null")
                    )
                    privileges = userLoginResponse.privileges
                    /*ToastUtils.show(userInfo.name)
                    ToastUtils.show(privileges.toString())*/
                }
            }
        }else{
            ToastUtils.show("请检查账号或密码是否为空")
        }
    }






}
